<template>
  <view class="container">
    <!-- 表单内容 -->
    <uni-forms ref="form" :model="addMerchantInfo">
      <!-- 个人信息部分 -->
      <uni-forms-item label="负责人姓名" name="merchantCode">
        <uni-easyinput v-model="addMerchantInfo.contactName" placeholder="请输入姓名"/>
      </uni-forms-item>

      <uni-forms-item label="负责人身份证号码" name="idCard">
        <uni-easyinput v-model="addMerchantInfo.idCardNumber" placeholder="请输入身份证号码"/>
      </uni-forms-item>

      <uni-forms-item label="负责人手机号" name="phone">
        <uni-easyinput v-model="addMerchantInfo.phoneNumber" placeholder="请输入手机号"/>
      </uni-forms-item>

      <!-- 店铺信息部分 -->
      <uni-forms-item label="营业时间" name="businessHours">
        <uni-easyinput v-model="addMerchantInfo.businessHours" placeholder="请输入营业时间"/>
      </uni-forms-item>
      <uni-forms-item label="店名" name="shopName">
        <uni-easyinput v-model="addMerchantInfo.shopName" placeholder="请输入店名"/>
      </uni-forms-item>
      <uni-forms-item label="工商营业执照号码" name="businessLicenseNumber">
        <uni-easyinput v-model="addMerchantInfo.businessLicenseNumber" placeholder="请输入营业执照号码"/>
      </uni-forms-item>

      <uni-forms-item label="经营区域" name="businessArea">
        <uni-easyinput v-model="addMerchantInfo.businessArea" placeholder="请输入经营区域"/>
      </uni-forms-item>
      <button @click="tomap">点击选择位置</button>
      <uni-forms-item label="详细地址" name="detailedAddress">
        <uni-easyinput v-model="addMerchantInfo.detailedAddress" placeholder="请输入详细地址"/>
      </uni-forms-item>


      <!-- 图片上传部分 -->
      <uni-section title="营业执照" type="line">
        <uni-file-picker v-model="formData.licensePhotos" fileMediatype="image" limit="2"/>
      </uni-section>

      <uni-section title="门面照片" type="line">
        <uni-file-picker v-model="formData.shopPhotos" fileMediatype="image" limit="4"/>
      </uni-section>

      <uni-section title="身份证正反面" type="line">
        <uni-file-picker ref="testref" v-model="testFileList" fileMediatype="image" @delete="handleDelete" limit="2"
                         name="testFileList" @select="select"/>
      </uni-section>
    </uni-forms>

    <!-- 底部操作按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">确认添加</button>
    </view>
  </view>
</template>

<script setup>
import {
  ref,
  onMounted
} from 'vue';
import {
  onLoad,
  onShow,
  onUnload,
  onBackPress
} from '@dcloudio/uni-app'
import {addmerchants} from '@/api/mcslf/merchants'
import {getToken} from '@/utils/auth'; // 引入 auth.js 中的 getToken 方法
onShow(() => {
  let res = uni.getStorageSync("testKey");
  console.log(res.currentLatitude.value);
  if (res) {
    addMerchantInfo.value.latitude = res.currentLatitude
    addMerchantInfo.value.longitude = res.currentLongitude
    console.log(addMerchantInfo.value.longitude);
  }

})
// 表单数据
const testref = ref();
const formData = ref({
  // 营业执照照片id（外键图片ID）
  // businessLicenseImageId: null,
  licensePhotos: [],
  licensePhotosFile: [],
  // 门面照片id（外键图片ID）
  // storefrontImageId: null,
  shopPhotos: [],
  shopPhotosFile: [],
  // 	// 身份证正反照id（外键图片ID）
  // idCardImageId: null,
  idCardPhotos: [],
  idCardPhotosFile: []
});
let testFileList = ref([])

// const currentLongitude = ref(116.397428)
// const currentLatitude = ref(39.90923)
// await uni.getStorageSync("testKey")
const addMerchantInfo = ref({
  // 自增
  merchantId: null,
  // 后台获取
  merchantCode: null,
  //  负责人姓名
  contactName: null,
  // 身份证号
  idCardNumber: null,
  // 营业执照编号
  businessLicenseNumber: null,
  // 店名
  shopName: null,
  // 手机号
  phoneNumber: null,
  // 经营区域
  businessArea: null,
  // 详细地址
  detailedAddress: null,
  // 身份证正反照id（外键图片ID）
  idCardImageId: null,
  // 营业执照照片id（外键图片ID）
  businessLicenseImageId: null,
  // 门面照片id（外键图片ID）
  storefrontImageId: null,
  // 经度
  longitude: null,
  // 维度
  latitude: null,
  // 审核状态
  auditStatus: null,
  // 营业时间
  businessHours: null,
  // userid
  userId: null,
  // 店铺余额
  shopBalance: null
})
const tomap = () => {
  // pages/common/map/index
  uni.navigateTo({
    url: '/pages/common/map/index'
  });
}
const select = (e) => {
  formData.value.idCardPhotosFile.push(e.tempFilePaths[0]);
  console.log(formData.value.idCardPhotosFile);
};
const handleDelete = (e) => {
  console.log('删除文件：', e);
}
// 提交添加信息
const handleSubmit = async () => {
  const token = getToken(); // 获取 token
  console.log("准备添加");
  // const files = filePicker
  // let res = await uploadImages(formData.value.idCardPhotosFile);
  try {
    console.log(addMerchantInfo.value)
    addmerchants(addMerchantInfo.value);
    // 这里添加提交逻辑
    // uni.uploadFile({
    //   url: 'http://localhost:8866/mcslf/images/upload', // 替换为你的接口地址
    //   filePath: formData.value.idCardPhotosFile,
    //   header: {
    //     Authorization: token, // 在请求头中添加 token
    //   },
    //   name: 'files', // 后端接收的字段名
    //   // success: (uploadRes) => resolve(JSON.parse(uploadRes.data)), // 解析返回的 JSON 数据
    //   // fail: (err) => reject(err), // 如果失败，直接返回错误信息
    // });

    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('提交失败:', error);
  }
};
// **上传图片**
const uploadImages = async (fileList) => {
  console.log(fileList);
  const token = getToken(); // 获取 token
  console.log("串串串串串串串串");
  if (fileList.length === 0) {
    uni.showToast({title: '请先上传图片', icon: 'none'});
    return null;
  }

  const uploadedUrls = [];

  // 使用 uni.uploadFile 上传文件
  for (let i = 0; i < fileList.length; i++) {
    console.log(file);
    const file = fileList[i];
    try {
      console.log("串串try串串串try串串串");
      const res = await new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'http://localhost:8866/mcslf/images/upload', // 替换为你的接口地址
          filePath: file.tempFilePaths[0],
          header: {
            Authorization: token, // 在请求头中添加 token
          },
          name: 'files', // 后端接收的字段名
          success: (uploadRes) => resolve(JSON.parse(uploadRes.data)), // 解析返回的 JSON 数据
          fail: (err) => reject(err), // 如果失败，直接返回错误信息
        });
      });

      if (res.code === 200) {
        uploadedUrls.push(res.data[0].parentId); // 获取图片 ID
      } else {
        uni.showToast({title: '上传失败', icon: 'none'});
        return null;
      }
    } catch (error) {
      console.error('上传失败，错误信息:', error); // 输出错误信息
      uni.showToast({title: '上传失败，请检查网络或文件', icon: 'none'});
      return null;
    }
  }

  return uploadedUrls[0]; // 返回第一张图片的 parentId
};

</script>

<style lang="scss">
.container {
  padding: 20 rpx 30 rpx 120 rpx;
  /* 增加底部内边距 */
  min-height: 100vh;
  box-sizing: border-box;
  /* 重要：防止padding影响布局 */
}

.uni-forms-item {
  margin-bottom: 20 rpx;
}

.textarea {
  width: 100%;
  min-height: 200 rpx;
  padding: 20 rpx;
  background-color: #f5f5f5;
  border-radius: 8 rpx;
}

.footer {
  position: relative;
  /* 改为相对定位 */
  padding: 20 rpx 0;
  background-color: #fff;

  /* 添加顶部边框线 */
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -30rpx;
    right: -30rpx;
    height: 2 rpx;
    background-color: #eee;
  }
}

.submit-btn {
  background-color: #007AFF;
  color: white;
  border-radius: 50 rpx;
  margin-top: 20 rpx;
}
</style>